package com.repair.controller;

import com.repair.entity.RepairOrder;
import com.repair.entity.User;
import com.repair.service.RepairOrderService;
import com.repair.service.UserService;
import com.repair.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import org.springframework.http.HttpStatus;
import java.time.LocalDate;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/api/repairman")
public class RepairmanController {

    @Autowired
    private UserService userService;

    @Autowired
    private RepairOrderService repairOrderService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> loginRequest) {
        String username = loginRequest.get("username");
        String password = loginRequest.get("password");
        
        User user = userService.getByUsername(username);
        if (user == null || user.getRole() != 2) {
            return ResponseEntity.badRequest().body("用户名或密码错误");
        }

        if (!passwordEncoder.matches(password, user.getPassword())) {
            return ResponseEntity.badRequest().body("用户名或密码错误");
        }

        if (user.getStatus() == 0) {
            return ResponseEntity.badRequest().body("账号已被禁用");
        }

        String token = jwtUtil.generateToken(user);
        Map<String, Object> response = new HashMap<>();
        response.put("token", token);
        response.put("user", user);
        return ResponseEntity.ok(response);
    }

    @GetMapping("/profile")
    public ResponseEntity<?> getProfile() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String username = auth.getName();
        User user = userService.getByUsername(username);
        
        if (user == null || user.getRole() != 2) {
            return ResponseEntity.badRequest().body("用户不存在或不是维修工");
        }

        return ResponseEntity.ok(user);
    }

    @PutMapping("/profile")
    public ResponseEntity<?> updateProfile(@RequestBody Map<String, Object> profile) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String username = auth.getName();
        User user = userService.getByUsername(username);
        
        if (user == null || user.getRole() != 2) {
            return ResponseEntity.badRequest().body("用户不存在或不是维修工");
        }

        user.setRealName((String) profile.get("realName"));
        user.setPhone((String) profile.get("phone"));
        user.setEmail((String) profile.get("email"));
        user.setAddress((String) profile.get("address"));

        userService.updateById(user);
        return ResponseEntity.ok(user);
    }

    @GetMapping("/orders")
    public ResponseEntity<?> getOrders(@RequestParam(required = false) Integer status) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String username = auth.getName();
        User user = userService.getByUsername(username);
        
        if (user == null || user.getRole() != 2) {
            return ResponseEntity.badRequest().body("用户不存在或不是维修工");
        }

        List<Map<String, Object>> orders;
        // 0待接单，1已接单，2维修中，3已完成，4已取消

        if (status == null) {
            orders = repairOrderService.getAllOrders();
            // 过滤掉不是本人接单的订单，保留维修工id是空的订单
            orders.removeIf(order -> {
                if (order.get("repairman_id") == null && (int)order.get("status") == 4) {
                    return true;
                }
                if (order.get("repairman_id") == null) {
                    return false;
                }
                return !(order.get("repairman_id")).equals(user.getId());
            });
            return ResponseEntity.ok(orders);
        }

        if (status == 0) {
            // 待接单
            orders = repairOrderService.getPendingOrders();
        } else if (status == 1) {
            // 已接单
            orders = repairOrderService.getAcceptedOrders(user.getId());
        } else if (status == 2) {
            orders = repairOrderService.getRepairingOrders(user.getId());
        } else if (status == 3) {
            orders = repairOrderService.getCompletedOrders(user.getId());
        } else if (status == 4) {
            orders = repairOrderService.getCancelledOrders(user.getId());
        } else {
            orders = repairOrderService.getAllOrders();
            // 过滤掉不是本人接单的订单，保留维修工id是空的订单
            orders.removeIf(order -> {
                if (order.get("repairman_id") == null) {
                    return false;
                }
                if (order.get("repairman_id") == null && order.get("status").equals(4)) {
                    return true;
                }
                return (order.get("repairman_id")).equals(user.getId());
            });
        }

        return ResponseEntity.ok(orders);
    }

    @GetMapping("/orders/{id}")
    public ResponseEntity<?> getOrderDetails(@PathVariable Long id) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String username = auth.getName();
        User user = userService.getByUsername(username);
        
        if (user == null || user.getRole() != 2) {
            return ResponseEntity.badRequest().body("用户不存在或不是维修工");
        }

        Map<String, Object> order = repairOrderService.getOrderDetails(id);
        return ResponseEntity.ok(order);
    }

    @PostMapping("/orders/{id}/accept")
    public ResponseEntity<?> acceptOrder(@PathVariable Long id) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String username = auth.getName();
        User user = userService.getByUsername(username);
        
        if (user == null || user.getRole() != 2) {
            return ResponseEntity.badRequest().body("用户不存在或不是维修工");
        }

        repairOrderService.acceptOrder(id, user.getId());
        return ResponseEntity.ok().build();
    }

    @PostMapping("/orders/{id}/complete")
    public ResponseEntity<?> completeOrder(@PathVariable Long id) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String username = auth.getName();
        User user = userService.getByUsername(username);
        
        if (user == null || user.getRole() != 2) {
            return ResponseEntity.badRequest().body("用户不存在或不是维修工");
        }

        repairOrderService.completeOrder(id);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/orders/{id}/start")
    public ResponseEntity<?> startRepair(@PathVariable Long id) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String username = auth.getName();
        User user = userService.getByUsername(username);
        
        if (user == null || user.getRole() != 2) {
            return ResponseEntity.badRequest().body("用户不存在或不是维修工");
        }

        repairOrderService.startRepair(id);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/location")
    public ResponseEntity<?> updateLocation(@RequestBody Map<String, Double> location) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String username = auth.getName();
        User user = userService.getByUsername(username);
        
        if (user == null || user.getRole() != 2) {
            return ResponseEntity.badRequest().body("用户不存在或不是维修工");
        }

        repairOrderService.updateRepairmanLocation(user.getId(), location.get("latitude"), location.get("longitude"));
        return ResponseEntity.ok().build();
    }

    @GetMapping("/statistics")
    public ResponseEntity<?> getStatistics() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String username = auth.getName();
        User user = userService.getByUsername(username);
        
        if (user == null || user.getRole() != 2) {
            return ResponseEntity.badRequest().body("用户不存在或不是维修工");
        }

        // 获取维修工的统计数据
        Map<String, Object> statistics = new HashMap<>();
        
        // 获取该维修工的所有订单
        List<RepairOrder> orders = repairOrderService.getRepairmanOrders(user.getId());
        
        // 计算总订单数
        statistics.put("totalOrders", orders.size());
        
        // 计算已完成订单数（状态为3表示已完成）
        long completedOrders = orders.stream()
                .filter(order -> order.getStatus() == 3)
                .count();
        statistics.put("completedOrders", completedOrders);
        
        // 计算待处理订单数（状态为1表示已接单但未开始维修）
        long pendingOrders = orders.stream()
                .filter(order -> order.getStatus() == 1)
                .count();
        statistics.put("pendingOrders", pendingOrders);
        
        // 计算今日订单数
        LocalDateTime startOfDay = LocalDate.now().atStartOfDay();
        long todayOrders = orders.stream()
                .filter(order -> order.getCreateTime().isAfter(startOfDay))
                .count();
        statistics.put("todayOrders", todayOrders);

        return ResponseEntity.ok(statistics);
    }
} 